/*
1.获取当前时间戳
2.判断文件是否存在
3.获取文件所在路径
4.创建目录
*/

#pragma once

#include <iostream>
#include <ctime>
#include <unistd.h>  // for access()
#include <sys/stat.h>  // for stat()
#include <string>

namespace xzt
{
    namespace log
    {
        namespace util
        {
            class Date
            {
            public:
                static time_t now()
                {
                    return time(nullptr);
                }
            };

            class File
            {
            public:
                static bool exists(const std::string& pathname)
                {
                    // just foe linux
                    // return access(path.c_str(), F_OK) == 0;

                    struct stat st;
                    return stat(pathname.c_str(), &st) == 0;
                }

                static size_t size(const std::string& pathname)
                {
                    struct stat st;
                    if(stat(pathname.c_str(), &st) == 0)
                    {
                        return st.st_size;
                    }
                    return 0;
                }

                static std::string path(const std::string& pathname)
                {
                    size_t pos = pathname.find_last_of("/\\");
                    if(pos == std::string::npos)  // 根目录
                    {
                        return "./";
                    }
                    return pathname.substr(0, pos + 1);
                }

                static void createDirectory(const std::string& path)
                {
                    // ./abc/def/ghi
                    int idx = 0, pos = 0;
                    while(idx < path.size())
                    {
                        pos = path.find_first_of("/\\", idx);
                        if(pos == std::string::npos)  // 到达最子目录
                        {
                            mkdir(path.substr(idx).c_str(), 0755);
                            break;
                        }
                        std::string parent_dir = path.substr(0, pos + 1);
                        if(exists(parent_dir) == false)
                        {
                            mkdir(parent_dir.c_str(), 0755);
                        }

                        idx = pos + 1;
                    }
                }
            };
        }
    }
}